package thread;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-09-24
 * Time: 19:22
 */
class MyBlockingQueue{
    //队列就是先进的先出，后进的后出
    private Object locker1 = new Object();
    private String[] elems = null;
    private int head = 0;
    private int tail = 0;
    private int size = 0;
    public MyBlockingQueue(int capacity){
        elems = new String[capacity];
    }

    public void put(String elem){
        if(size >= elems.length){
            //队列满了进行阻塞
            return;
        }
        //放元素
        elems[tail] = elem;
        tail++;
        if (tail >= elems.length){
            tail = 0;
        }
        size++;
    }

    public String take(){
        if(size == 0){
            //队列为空进行阻塞
            return null;
        }
        String elem = elems[head];
        head++;
        if (head >= elems.length){
            head = 0;
        }
        size--;
        return elem;
    }
}
public class ThreadDemon30 {

    public static void main(String[] args) {
        /*MyBlockingQueue queue = new MyBlockingQueue(100);
        queue.put("aaa");//放aaa一直放到ddd
        queue.put("bbb");
        queue.put("ccc");
        queue.put("ddd");

        String elem = "test";
        System.out.println(queue.take());//出队列先放的先出
        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());*/

        ArrayBlockingQueue queue2 = new ArrayBlockingQueue<>(100);
        try {
            queue2.put("put方法不带阻塞功能");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        queue2.offer("offer方法带有阻塞功能");

        try {
            System.out.println(queue2.take());
            System.out.println(queue2.take());

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }


    }


}
